package com.sise.thread.lab02;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * 作者：idea
 * 日期：2018/6/21
 * 描述：
 */
public class ConcurrentHashMaps {

    public static void main(String[] args) throws InterruptedException {
//        final Map<String,Integer> count=  new HashMap<>();
//        final CountDownLatch endLatch=new CountDownLatch(2);
//        Runnable task=new Runnable() {
//            @Override
//            public void run() {
//                for(int i=0;i<5;i++){
//                    Integer value=count.get("a");
//                    if(value==null){
//                        count.put("a",1);
//                    }else{
//                        count.put("a",value+1);
//                    }
//                }
//                endLatch.countDown();
//            }
//        };
//        new Thread(task).start();
//        new Thread(task).start();
//        endLatch.await();
//        System.out.println(count);
        final Map<String, Integer> count = new ConcurrentHashMap<>();
        final CountDownLatch endLatch = new CountDownLatch(2);
        Runnable task = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    Integer value = count.get("a");
                    if (null == value) {
                        count.put("a", 1);
                    } else {
                        count.put("a", value + 1);
                    }
                }
                endLatch.countDown();
            }
        };
        new Thread(task).start();
        new Thread(task).start();

        try {
            endLatch.await();
            System.out.println(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
